
//日期转换
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var WfPowerSk = null;//风电场功率实况表
var WfNwp = null;//风电场天气预报数据（取风速）
var WfMetSk = null;//测风塔数据表（取风速）
var startTime = null;       //开始时间，表格导出数据使用
var endTime = null;         //结束时间，表格导出数据使用
var farmName = null;       //电场名称，表格导出数据使用
var fileName = null;
$(function () {
    //$.ajaxSettings.async = false;
    showDiv();
    dateTiemSelect();
    dateTiemSelect2();
    $("#query").click(function () {
        if($("#startTime").val()===""||$("#endTime").val()===""){
            layer.msg("时间不完整！", {icon: 2});
            $("#queryData").bootstrapTable("destroy");
            new tableFactory();
            return;
        }
        var startTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
        if(startTime >=endTime){
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime").val("");
            $("#endTime").val("");
            return false;
        }else {
            load();
        }
    })
    $("#query2").click(function () {
        // alert("111");
        if($("#startTime2").val()===""){
            layer.msg("输入开始时间！", {icon: 2});
            $("#endTime2").val("");
        }
        var startTime = new Date($("#startTime2").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime2").val().replace(/\-/g, "\/"));
        if(startTime >=endTime){
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime2").val("");
            $("#endTime2").val("");
            return false;
        }else {
            load();
        }
    })
    var options=$("#cs option:selected");//获取id为"cs"的选中的项

    var aa = $('#selectFarm', window.parent.document).find("option:selected").text();
    console.log(aa);
    //  fileName = aa.substring(31,aa.length);
    // console.log(fileName);
    if(options.val() == 4){
        startTime = $("#startTime").val();
        endTime = $("#endTime").val();
    }
    if(options.val() == 5){
        startTime = $("#startTime2").val();
        endTime = $("#endTime2").val();
    }

    var table = new tableFactory(startTime,endTime,aa);
})

//点击时间查询
function dateTiemSelect(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime', //新增的日期
            type: 'date',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#20284D',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime', //新增的日期
            type: 'date',
            theme: '#20284D',//自定义主题
            ready: function(date){
            },
            done: function(value, date, endDate){//选中之后的对调函数

            }
        });
    });
}
//点击时间查询
function dateTiemSelect2(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime2', //新增的日期
            type: 'month',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#20284D',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime2', //新增的日期
            type: 'month',
            theme: '#20284D',//自定义主题
            max: '2028-12-31',//限制最大日期
            ready: function(date){

            },
            done: function(value, date, endDate){//选中之后的对调函数

            }
        });
    });
}
function load(){
    var index = layer.load(1);
    var date = new Array();//观测时间
    var options=$("#cs option:selected");//获取id为"cs"的选中的项
    var farmid = $('#selectFarm', window.parent.document).val();//获取父页面的元素
    var synthesize = new Array();
    var j = 0;
    if(options.val() == 4){
        var p = {
            "startTime":$("#startTime").val(),
            "endTime":$("#endTime").val(),
            "farmid":farmid
        };
        $.ajax({
            url : "../historicalDataManage/getSFHistoryDataDay",
            type : "get",
            contentType : "application/json",
            dataType : "json",
            data : p/*JSON.stringify(p)*/,//转换成字符串。后台使用了RequestBody注解
            success : function(data) {
                console.log(data);
                synthesize = data.listSfMetSk;
                //计算最大值
                var totalradiationMax = 0;
                var directradiationMax = 0;
                var scatterdradiationMax = 0;
                var windspeedMax = 0;
                var winddirectionMax = 0;
                var pressureMax = 0;
                var tempMax = 0;
                var humidityMax = 0;
                //计算最大值出现日期
                var totalradiationDate = 0;
                var directradiationDate = 0;
                var scatterdradiationDate = 0;
                var windspeedDate = 0;
                var winddirectionDate = 0;
                var pressureDate = 0;
                var tempDate = 0;
                var humidityDate = 0;
                for (var i in synthesize) {
                    if(totalradiationMax < synthesize[i].totalradiation){
                        totalradiationMax = synthesize[i].totalradiation;
                        totalradiationDate = synthesize[i].observetime;
                    }
                    if(directradiationMax < synthesize[i].directradiation){
                        directradiationMax = synthesize[i].directradiation;
                        directradiationDate = synthesize[i].observetime;
                    }
                    if(scatterdradiationMax < synthesize[i].scatterdradiation){
                        scatterdradiationMax = synthesize[i].scatterdradiation;
                        scatterdradiationDate = synthesize[i].observetime;
                    }
                    if(windspeedMax < synthesize[i].windspeed){
                        windspeedMax = synthesize[i].windspeed;
                        windspeedDate = synthesize[i].observetime;
                    }
                    if(winddirectionMax < synthesize[i].winddirection){
                        winddirectionMax = synthesize[i].winddirection;
                        winddirectionDate = synthesize[i].observetime;
                    }
                    if(pressureMax < synthesize[i].pressure){
                        pressureMax = synthesize[i].pressure;
                        pressureDate = synthesize[i].observetime;
                    }
                    if(tempMax < synthesize[i].temp){
                        tempMax = synthesize[i].temp;
                        tempDate = synthesize[i].observetime;
                    }
                    if(humidityMax < synthesize[i].humidity){
                        humidityMax = synthesize[i].humidity;
                        humidityDate = synthesize[i].observetime;
                    }
                }
                //计算平均值
                var totalradiationAverage = 0;
                var directradiationAverage = 0;
                var scatterdradiationAverage = 0;
                var windspeedAverage = 0;
                var winddirectionAverage = 0;
                var pressureAverage = 0;
                var tempAverage = 0;
                var humidityAverage = 0;
                j = 0;
                for (var i in synthesize) {
                    totalradiationAverage += synthesize[i].totalradiation;
                    directradiationAverage += synthesize[i].directradiation;
                    scatterdradiationAverage += synthesize[i].scatterdradiation;
                    windspeedAverage += synthesize[i].windspeed;
                    winddirectionAverage += synthesize[i].winddirection;
                    pressureAverage += synthesize[i].pressure;
                    tempAverage += synthesize[i].temp;
                    humidityAverage += synthesize[i].humidity;
                    j++;
                }
                totalradiationAverage = totalradiationAverage/j;
                directradiationAverage = directradiationAverage/j;
                scatterdradiationAverage = scatterdradiationAverage/j;
                windspeedAverage = windspeedAverage/j;
                winddirectionAverage = winddirectionAverage/j;
                pressureAverage = pressureAverage/j;
                tempAverage = tempAverage/j;
                humidityAverage = humidityAverage/j;
                //-----------------------------------


                var a={observetime:'最大值',totalradiation:totalradiationMax,directradiation:directradiationMax,scatterdradiation:scatterdradiationMax,windspeed:windspeedMax,winddirection:winddirectionMax,pressure:pressureMax,temp:tempMax,humidity:humidityMax}
                var b={observetime:'平均值',totalradiation:totalradiationAverage,directradiation:directradiationAverage,scatterdradiation:scatterdradiationAverage,windspeed:windspeedAverage,winddirection:winddirectionAverage,pressure:pressureAverage,temp:tempAverage,humidity:humidityAverage}
                var c={observetime:'最大值出现日期',totalradiation:totalradiationDate,directradiation:directradiationDate,scatterdradiation:scatterdradiationDate,windspeed:windspeedDate,winddirection:winddirectionDate,pressure:pressureDate,temp:tempDate,humidity:humidityDate}
                synthesize.push(a);
                synthesize.push(b);
                synthesize.push(c);

                $("#queryData").bootstrapTable("load", synthesize);
                layer.close(index);
            },
            error :function(){
                layer.msg("没有找到数据！", {icon: 2});
            }
        });
    }
    if(options.val() == 5){
        var p = {
            "startTime":$("#startTime2").val(),
            "endTime":$("#endTime2").val(),
            "farmid":farmid
        };
        $.ajax({
            url : "../historicalDataManage/getSFHistoryDataMonth",
            type : "get",
            contentType : "application/json",
            dataType : "json",
            data : p/*JSON.stringify(p)*/,//转换成字符串。后台使用了RequestBody注解
            success : function(data) {
                synthesize = data.listSfMetSk;
                //计算最大值
                var totalradiationMax = 0;
                var directradiationMax = 0;
                var scatterdradiationMax = 0;
                var windspeedMax = 0;
                var winddirectionMax = 0;
                var pressureMax = 0;
                var tempMax = 0;
                var humidityMax = 0;
                //计算最大值出现日期
                var totalradiationDate = 0;
                var directradiationDate = 0;
                var scatterdradiationDate = 0;
                var windspeedDate = 0;
                var winddirectionDate = 0;
                var pressureDate = 0;
                var tempDate = 0;
                var humidityDate = 0;
                for (var i in synthesize) {
                    if(totalradiationMax < synthesize[i].totalradiation){
                        totalradiationMax = synthesize[i].totalradiation;
                        totalradiationDate = synthesize[i].observetime;
                    }
                    if(directradiationMax < synthesize[i].directradiation){
                        directradiationMax = synthesize[i].directradiation;
                        directradiationDate = synthesize[i].observetime;
                    }
                    if(scatterdradiationMax < synthesize[i].scatterdradiation){
                        scatterdradiationMax = synthesize[i].scatterdradiation;
                        scatterdradiationDate = synthesize[i].observetime;
                    }
                    if(windspeedMax < synthesize[i].windspeed){
                        windspeedMax = synthesize[i].windspeed;
                        windspeedDate = synthesize[i].observetime;
                    }
                    if(winddirectionMax < synthesize[i].winddirection){
                        winddirectionMax = synthesize[i].winddirection;
                        winddirectionDate = synthesize[i].observetime;
                    }
                    if(pressureMax < synthesize[i].pressure){
                        pressureMax = synthesize[i].pressure;
                        pressureDate = synthesize[i].observetime;
                    }
                    if(tempMax < synthesize[i].temp){
                        tempMax = synthesize[i].temp;
                        tempDate = synthesize[i].observetime;
                    }
                    if(humidityMax < synthesize[i].humidity){
                        humidityMax = synthesize[i].humidity;
                        humidityDate = synthesize[i].observetime;
                    }
                }
                //计算平均值
                var totalradiationAverage = 0;
                var directradiationAverage = 0;
                var scatterdradiationAverage = 0;
                var windspeedAverage = 0;
                var winddirectionAverage = 0;
                var pressureAverage = 0;
                var tempAverage = 0;
                var humidityAverage = 0;
                j = 0;
                for (var i in synthesize) {
                    totalradiationAverage += synthesize[i].totalradiation;
                    directradiationAverage += synthesize[i].directradiation;
                    scatterdradiationAverage += synthesize[i].scatterdradiation;
                    windspeedAverage += synthesize[i].windspeed;
                    winddirectionAverage += synthesize[i].winddirection;
                    pressureAverage += synthesize[i].pressure;
                    tempAverage += synthesize[i].temp;
                    humidityAverage += synthesize[i].humidity;
                    j++;
                }
                totalradiationAverage = totalradiationAverage/j;
                directradiationAverage = directradiationAverage/j;
                scatterdradiationAverage = scatterdradiationAverage/j;
                windspeedAverage = windspeedAverage/j;
                winddirectionAverage = winddirectionAverage/j;
                pressureAverage = pressureAverage/j;
                tempAverage = tempAverage/j;
                humidityAverage = humidityAverage/j;
                //-----------------------------------


                var a={observetime:'最大值',totalradiation:totalradiationMax,directradiation:directradiationMax,scatterdradiation:scatterdradiationMax,windspeed:windspeedMax,winddirection:winddirectionMax,pressure:pressureMax,temp:tempMax,humidity:humidityMax}
                var b={observetime:'平均值',totalradiation:totalradiationAverage,directradiation:directradiationAverage,scatterdradiation:scatterdradiationAverage,windspeed:windspeedAverage,winddirection:winddirectionAverage,pressure:pressureAverage,temp:tempAverage,humidity:humidityAverage}
                var c={observetime:'最大值出现日期',totalradiation:totalradiationDate,directradiation:directradiationDate,scatterdradiation:scatterdradiationDate,windspeed:windspeedDate,winddirection:winddirectionDate,pressure:pressureDate,temp:tempDate,humidity:humidityDate}
                synthesize.push(a);
                synthesize.push(b);
                synthesize.push(c);

                $("#queryData").bootstrapTable("load", synthesize);
                layer.close(index);
            },
            error :function(){
                layer.msg("没有找到数据！", {icon: 2});
            }
        });
    }


}

function tableFactory(startTime,endTime,fileNames) {
    var me = this;
    me.data = null;//有功功率
    me.windData = null;//电站信息
    var init = function () {
            $("#queryData").bootstrapTable({
                method: 'get',				  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                //showFooter: true,               //显示统计
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "desc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect:true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 20,
                pageList: [5,20,30],
                editable:true,//是否可以行内编辑
                showExport: true,//是否显示导出按钮
                exportDataType:'all',//导出全部
                exportTypes:[  'csv'], //导出文件类型
                export: 'glyphicon-export icon-share',
                exportOptions:{
                    // ignoreColumn: [0,1],  //忽略某一列的索引
                    fileName:startTime+"_"+endTime+"_"+fileNames,  //文件名称设置
                    // worksheetName: 'sheet1',  //表格工作区名称
                    // tableName: '总台帐报表',
                    //  excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
                    // onMsoNumberFormat: DoOnMsoNumberFormat
                },
                columns: [{
                    title: '时间',
                    field: 'observetime',
                    sortable: true,//排序
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        if(value == '最大值'){
                            return '最大值';
                        }else if(value == '平均值'){
                            return '平均值';
                        }else if(value == '最大值出现日期'){
                            return '最大值出现日期';
                        }else {
                            return new Date(parseInt(value)).Format("yyyy-MM-dd hh:mm");
                        }
                    },
                },
                    {
                        title: '总辐射(W/㎡)',
                        field: 'totalradiation',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }

                        },
                        /*footerFormatter: function (value) {
                            var count = 0;
                            for (var i in value) {
                                if(count <= value[i].totalradiation){
                                    count = value[i].totalradiation;
                                }
                            }
                            return count;
                        },*/

                    }, {
                        title: '直接辐射(W/㎡)',
                        field: 'directradiation',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },

                    },
                    {
                        title: '散射辐照度(W/㎡)',
                        field: 'scatterdradiation',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    }, {
                        title: '风速(m/s)',
                        field: 'windspeed',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    }, {
                        title: '风向(°)',
                        field: 'winddirection',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    }, {
                        title: '气压(hPa)',
                        field: 'pressure',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    }, {
                        title: '温度(℃)',
                        field: 'temp',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    }, {
                        title: '湿度(%)',
                        field: 'humidity',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        },
                    },{
                        title: '实况(W/m)',
                        field: 'activepower',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        }
                    },{
                        title: '预报(W/m)',
                        field: 'power',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            if(value == null){
                                return "-";
                            }else if(row.observetime == '最大值出现日期'){
                                if(value == 0){
                                    return '无数据';
                                }else {
                                    return new Date(parseInt(value)).Format("yyyy-MM-dd");
                                }
                            }else {
                                return value.toFixed(2);
                            }
                        }
                    }
                ],
            });
           load();

    }
    init();
}

/**
 * 合并行
 * @param data  原始数据（在服务端完成排序）
 * @param fieldName 合并属性名称数组
 * @param colspan 列数
 * @param target 目标表格对象
 */
function mergeCells(data, fieldName, colspan, target) {
    if (data.length == 0) {
        alert("不能传入空数据");
        return;
    }
    var numArr = [];
    var value = data[0][fieldName];
    var num = 0;
    for (var i = 0; i < data.length; i++) {
        if (value != data[i][fieldName]) {
            numArr.push(num);
            value = data[i][fieldName];
            num = 1;
            continue;
        }
        num++;
    }
    var merIndex = 0;
    for (var i = 0; i < numArr.length; i++) {
        $(target).bootstrapTable('mergeCells', { index: merIndex, field: fieldName, colspan: colspan, rowspan: numArr[i] })
        merIndex += numArr[i];
    }
}

tableFactory.prototype = {


    getData:function () {

    },

}
function real(){
    window.location.reload();
}

function showDiv() {
    $("select").change(function(){
        var selectedValue=$(this).val();

        if(selectedValue==4){

            $("#box1").show();

            $("#box2").hide();
        }
        if(selectedValue==5){

            $("#box2").show();

            $("#box1").hide();
        }
    });
}



